package zijie;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 */
public class MergeTwoLists_21_14 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode pre = new ListNode(-1);
        ListNode head = pre;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                head.next = l1;
                l1 = l1.next;
            }else {
                head.next = l2;
                l2 = l2.next;
            }
            head = head.next;
        }
        head.next = l1 == null ? l2:l1;
        return pre.next;
    }

    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode pre = new ListNode(-1);
        ListNode head = pre;
        while (l1 != null && l2 != null){
            if(l1.val < l2.val) {
                head.next = l1;
                l1 = l1.next;
            } else{
                head.next = l2;
                l2 = l2.next;
            }
            head = head.next;
        }
        head.next = l1 == null ? l2 : l1;
        return  pre.next;

    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        MergeTwoLists_21_14 reverseList_206 = new MergeTwoLists_21_14();
        MergeTwoLists_21_14.ListNode a = new MergeTwoLists_21_14.ListNode(1);
        MergeTwoLists_21_14.ListNode b = new MergeTwoLists_21_14.ListNode(2);
        MergeTwoLists_21_14.ListNode d = new MergeTwoLists_21_14.ListNode(4);
        MergeTwoLists_21_14.ListNode e = new MergeTwoLists_21_14.ListNode(5);
        a.next = b;
        b.next = d;
        d.next = e;

        MergeTwoLists_21_14.ListNode a1 = new MergeTwoLists_21_14.ListNode(1);
        MergeTwoLists_21_14.ListNode b1 = new MergeTwoLists_21_14.ListNode(2);
        MergeTwoLists_21_14.ListNode c1 = new MergeTwoLists_21_14.ListNode(3);
        a1.next = b1;
        b1.next = c1;
        reverseList_206.mergeTwoLists(a, a1);
    }
}
